// 调试数据库数据
async function debugDatabase() {
    const dbName = 'PaymentRecordsDB';
    const version = 1;

    return new Promise((resolve, reject) => {
        const request = indexedDB.open(dbName, version);

        request.onsuccess = function (event) {
            const db = event.target.result;
            const transaction = db.transaction(['payment_records'], 'readonly');
            const store = transaction.objectStore('payment_records');
            const getAllRequest = store.getAll();

            getAllRequest.onsuccess = function () {
                const allRecords = getAllRequest.result;
                console.log('=== 数据库中的所有记录 ===');

                // 过滤会员10001的记录
                const memberRecords = allRecords.filter(r => r.member_id === '10001');
                console.log('会员10001的记录数量:', memberRecords.length);

                memberRecords.forEach((record, index) => {
                    console.log(`[${index + 1}] ID: ${record.id}`);
                    console.log(`    类型: ${record.payment_type}`);
                    console.log(`    金额: ${record.amount} (类型: ${typeof record.amount})`);
                    console.log(`    余额: ${record.balance}`);
                    console.log(`    状态: ${record.status}`);
                    console.log(`    时间: ${record.payment_date}`);
                    console.log(`    是否撤销: ${record.is_revoked}`);
                    console.log(`    关联记录: ${record.related_record_id || 'N/A'}`);
                    console.log('    ---');
                });

                // 特别检查REVERSE记录
                const reverseRecords = memberRecords.filter(r => r.id.startsWith('REVERSE'));
                console.log('=== REVERSE记录详情 ===');
                reverseRecords.forEach(record => {
                    console.log(`REVERSE记录: ${record.id}`);
                    console.log(`  payment_type: ${record.payment_type}`);
                    console.log(`  amount: ${record.amount} (${typeof record.amount})`);
                    console.log(`  related_record_id: ${record.related_record_id}`);
                });

                resolve(memberRecords);
            };

            getAllRequest.onerror = function () {
                console.error('获取数据失败');
                reject(getAllRequest.error);
            };
        };

        request.onerror = function () {
            console.error('打开数据库失败');
            reject(request.error);
        };
    });
}

// 手动计算余额
function manualCalculateBalance(records) {
    console.log('=== 手动计算余额 ===');

    // 过滤有效记录
    const validRecords = records.filter(r => r.status !== 'revoked');
    console.log('有效记录数量:', validRecords.length);

    // 按时间排序
    const sortedRecords = validRecords.sort((a, b) => {
        const normalizeDate = (dateStr) => {
            return dateStr.replace(/(\d{4})\/(\d{1,2})\/(\d{1,2})/, (match, year, month, day) => {
                return `${year}-${month.padStart(2, '0')}-${day.padStart(2, '0')}`;
            });
        };

        const dateA = new Date(normalizeDate(a.payment_date)).getTime();
        const dateB = new Date(normalizeDate(b.payment_date)).getTime();
        return dateA - dateB;
    });

    console.log('排序后的记录:');
    sortedRecords.forEach((record, index) => {
        console.log(`${index + 1}. ${record.id} - ${record.payment_type} - ${record.amount} - ${record.payment_date}`);
    });

    // 计算余额
    let balance = 0;
    console.log('=== 逐步计算 ===');
    sortedRecords.forEach((record, index) => {
        const amount = Number(record.amount);
        const oldBalance = balance;

        if (record.payment_type === 'recharge') {
            balance += amount;
        } else if (record.payment_type === 'deduction') {
            balance -= amount;
        }

        console.log(`步骤 ${index + 1}: ${record.id}`);
        console.log(`  类型: ${record.payment_type}`);
        console.log(`  金额: ${amount}`);
        console.log(`  操作: ${record.payment_type === 'recharge' ? '+' : '-'}${amount}`);
        console.log(`  余额: ${oldBalance} → ${balance}`);
        console.log('  ---');
    });

    console.log(`最终余额: ${balance}`);
    return balance;
}

// 运行调试
debugDatabase().then(records => {
    manualCalculateBalance(records);
}).catch(error => {
    console.error('调试失败:', error);
});

console.log('请打开控制台查看详细信息');
